//
//  WOAFNetWorkingHandle.m
//  MedicalAlarmSystem
//
//  Created by 吴欧 on 2017/8/31.
//  Copyright © 2017年 吴欧. All rights reserved.
//

#import "WOAFNetWorkingHandle.h"
#import "HELoginViewController.h"

#define NSStringFormat(format,...) [NSString stringWithFormat:format,##__VA_ARGS__]

static NSMutableArray *_allSessionTask;

static AFHTTPSessionManager *_sessionManager;

@implementation WOAFNetWorkingHandle

#pragma mark - life cycle
#pragma mark 初始化AFHTTPSessionManager相关属性

+ (void)load {
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
}

+ (void)initialize {

    _sessionManager = [AFHTTPSessionManager manager];
    _sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];//设置返回数据为json
    _sessionManager.requestSerializer.stringEncoding = NSUTF8StringEncoding;
    [_sessionManager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    _sessionManager.requestSerializer.timeoutInterval = 60.f;
    [_sessionManager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    _sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithArray:@[@"application/json",
                                                                              @"text/html",
                                                                              @"text/json",
                                                                              @"text/plain",
                                                                              @"text/javascript",
                                                                              @"text/xml",
                                                                              @"image/*"]];
    // https免签方式
//    _sessionManager.securityPolicy.allowInvalidCertificates = YES;
//    _sessionManager.securityPolicy.validatesDomainName = NO;
    
    // 验证证书
//    [_sessionManager setSecurityPolicy:[WOAFNetWorkingHandle customSecurityPolicy]];
}

#pragma mark - 支持https
+ (AFSecurityPolicy *)customSecurityPolicy
{
    //先导入证书，找到证书的路径   client bitvalue
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"bitvalue" ofType:@"cer"];
    NSData *certData = [NSData dataWithContentsOfFile:cerPath];
    
    //AFSSLPinningModeCertificate 使用证书验证模式
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    
    //allowInvalidCertificates 是否允许无效证书（也就是自建的证书），默认为NO
    //如果是需要验证自建证书，需要设置为YES
    securityPolicy.allowInvalidCertificates = YES;
    
    //validatesDomainName 是否需要验证域名，默认为YES；
    //假如证书的域名与你请求的域名不一致，需把该项设置为NO；如设成NO的话，即服务器使用其他可信任机构颁发的证书，也可以建立连接，这个非常危险，建议打开。
    //置为NO，主要用于这种情况：客户端请求的是子域名，而证书上的是另外一个域名。因为SSL证书上的域名是独立的，假如证书上注册的域名是www.google.com，那么mail.google.com是无法验证通过的；当然，有钱可以注册通配符的域名*.google.com，但这个还是比较贵的。
    //如置为NO，建议自己添加对应域名的校验逻辑。
    securityPolicy.validatesDomainName = NO;
    NSSet *set = [[NSSet alloc] initWithObjects:certData, nil];
    securityPolicy.pinnedCertificates = set;
    
    return securityPolicy;
}

#pragma mark - POST
+ (NSURLSessionTask *)POSTWithBaseUrl:(NSString *)baseUrl
                            suffixUrl:(NSString *)suffixUrl
                           parameters:(id)parameter
                                token: (NSString *)token
                              success:(WOHttpRquestSuccess)success
                              failure:(WOHttpRequestFailed)failure {
    // 拼接成完整的url
     baseUrl = [NSString stringWithFormat:@"%@%@",baseUrl,suffixUrl.length == 0 ? @"" : suffixUrl];
     
     // 将参数转换为字典
     NSDictionary *parameters = [parameter mj_keyValues];
     
     [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
     [SVProgressHUD show];

     NSLog(@"\n parameters ：%@ \n URL: %@",parameters,baseUrl);
     // AFJSONRequestSerializer
     _sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
     [_sessionManager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

    NSMutableDictionary *heards = [NSMutableDictionary dictionary];

    if (token != nil) {
        [heards setObject:[NSString stringWithFormat:@"Bearer %@",token] forKey:@"Authorization"];
    }
      NSURLSessionTask *sessionTask = [_sessionManager POST:baseUrl parameters:parameters headers:heards  progress:^(NSProgress * _Nonnull uploadProgress) {
           
       } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

           // 取消指示器
           [SVProgressHUD dismissWithDelay:0.1];
                 
           [[self allSessionTask] removeObject:task];
           
           NSDictionary *response = (NSDictionary *)responseObject;

           NSInteger code = ((NSNumber *)response[@"code"]).integerValue;
           if (code == 203) {
               [Dialog toast:@"登录成功" delay:2];
           }else if(code == 101) {
               
           }else {
               NSString *msg = (NSString *)responseObject[@"message"];
               if (![DYTools isBlankString:msg]) {
                   [Dialog toast:(NSString *)responseObject[@"message"] delay:2];
               }
           }

           success ? success(responseObject) : nil;
       } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
           DLog(@"error ： %@",error);

           [[self allSessionTask] removeObject:task];
           
           // 请求失败提示
           [self errorDomainTips:error];

           failure ? failure(error) : nil;
       }];
    
       
       // 添加最新的sessionTask到数组
       sessionTask ? [[self allSessionTask] addObject:sessionTask] : nil ;
       
       return sessionTask;
    
}

#pragma mark - POST
+ (NSURLSessionTask *)POSTWithBaseUrl:(NSString *)baseUrl
                            suffixUrl:(NSString *)suffixUrl
                           parameters:(id)parameter
                              success:(WOHttpRquestSuccess)success
                              failure:(WOHttpRequestFailed)failure {
    
    // 拼接成完整的url
    baseUrl = [NSString stringWithFormat:@"%@%@",baseUrl,suffixUrl.length == 0 ? @"" : suffixUrl];
    
    // 将参数转换为字典
    NSDictionary *parameters = [parameter mj_keyValues];
    
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    [SVProgressHUD show];

    NSLog(@"\n parameters ：%@ \n URL: %@",parameters,baseUrl);
    // AFJSONRequestSerializer
    _sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
    [_sessionManager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

    NSMutableDictionary *heards = [NSMutableDictionary dictionary];
    NSString *token = [[UserManager sharedUserManager] getToken];

    if (token != nil) {
        [heards setObject:[NSString stringWithFormat:@"Bearer %@",token] forKey:@"Authorization"];
    }
    
    NSURLSessionTask *sessionTask = [_sessionManager POST:baseUrl parameters:parameters headers:heards  progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        // 取消指示器
        [SVProgressHUD dismissWithDelay:0.1];
              
        [[self allSessionTask] removeObject:task];
        
        NSDictionary *response = (NSDictionary *)responseObject;

        NSInteger code = ((NSNumber *)response[@"code"]).integerValue;
        if (code == 203) {
            [Dialog toast:@"登录成功" delay:2];
        }else if(code == 101) {
            
        }else {
            NSString *messageText = (NSString *)responseObject[@"message"];
            if ([DYTools isBlankString:messageText]) {
                [Dialog toast:@"请求失败" delay:2];
            }else {
                [Dialog toast:(NSString *)responseObject[@"message"] delay:2];
            }
        }
        
        if (code == 201) {
            [[UserManager sharedUserManager] logout:^(BOOL success, NSString *des) {
            }];
        }

        success ? success(responseObject) : nil;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DLog(@"error ： %@",error);

        [[self allSessionTask] removeObject:task];
        
        // 请求失败提示
        [self errorDomainTips:error];

        failure ? failure(error) : nil;
    }];
 
    
    // 添加最新的sessionTask到数组
    sessionTask ? [[self allSessionTask] addObject:sessionTask] : nil ;
    
    return sessionTask;
}

+ (__kindof NSURLSessionTask *)POSTNoHUDWithBaseUrl:(NSString *)baseUrl
                                          suffixUrl:(NSString *)suffixUrl
                                         parameters:(id)parameter
                                            success:(WOHttpRquestSuccess)success
                                            failure:(WOHttpRequestFailed)failure {
            
    // 拼接成完整的url
    baseUrl = [NSString stringWithFormat:@"%@%@",baseUrl,suffixUrl.length == 0 ? @"" : suffixUrl];
    
    // 将参数转换为字典
    NSDictionary *parameters = [parameter mj_keyValues];
    
    NSLog(@"\n parameters ：%@ \n URL: %@",parameters,baseUrl);
 
    _sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
    [_sessionManager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

    NSMutableDictionary *heards = [NSMutableDictionary dictionary];
    NSString *token = [[UserManager sharedUserManager] getToken];

    if (token != nil) {
        [heards setObject:[NSString stringWithFormat:@"Bearer %@",token] forKey:@"Authorization"];
    }
    
    NSURLSessionTask *sessionTask = [_sessionManager POST:baseUrl parameters:parameters headers:heards  progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
 
        [[self allSessionTask] removeObject:task];

        NSDictionary *response = (NSDictionary *)responseObject;

        NSInteger code = ((NSNumber *)response[@"code"]).integerValue;
        if (code == 203) {
          [Dialog toast:@"登录成功" delay:2];
        }else if(code == 101) {
          
        }else {
          [Dialog toast:(NSString *)responseObject[@"message"] delay:2];
        }

        if (code == 201) {
          [[UserManager sharedUserManager] logout:^(BOOL success, NSString *des) {
          }];
        }

        success ? success(responseObject) : nil;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"error ： %@",error);
        
        [[self allSessionTask] removeObject:task];
        
        failure ? failure(error) : nil;
    }];
    
    // 添加最新的sessionTask到数组
    sessionTask ? [[self allSessionTask] addObject:sessionTask] : nil ;
    
    return sessionTask;
}


#pragma mark - key=value POST
// key=value形式传参数
+ (__kindof NSURLSessionTask *)POSTWithBaseUrlByKeyValue:(NSString *)baseUrl
                                          suffixUrl:(NSString *)suffixUrl
                                         parameters:(id)parameter
                                            success:(WOHttpRquestSuccess)success
                                            failure:(WOHttpRequestFailed)failure {
    
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    [SVProgressHUD show];
           
    // 拼接成完整的url
    baseUrl = [NSString stringWithFormat:@"%@%@",baseUrl,suffixUrl.length == 0 ? @"" : suffixUrl];

    // 将参数转换为字典
    NSDictionary *parameters = [parameter mj_keyValues];

    NSLog(@"\n parameters ：%@ \n URL: %@",parameters,baseUrl);

    /***
    AFHTTPRequestSerializer：第一种是普通的http的编码格式也就是mid=10&method=userInfo&dateInt=20160818，这种格式的。
    AFJSONRequestSerializer：第二种也是json编码格式的，也就是编码成{“mid”:“11”,“method”:“userInfo”,“dateInt”:“20160818”}
    AFPropertyListRequestSerializer：第三种没用过，但是看介绍接编码成pislt格式的参数
    */
    _sessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
    [_sessionManager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

    NSMutableDictionary *heards = [NSMutableDictionary dictionary];
    NSString *token = [[UserManager sharedUserManager] getToken];

    if (token != nil) {
       [heards setObject:[NSString stringWithFormat:@"Bearer %@",token] forKey:@"Authorization"];
    }

    NSURLSessionTask *sessionTask = [_sessionManager POST:baseUrl parameters:parameters headers:heards  progress:^(NSProgress * _Nonnull uploadProgress) {
       
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // 取消指示器
        [SVProgressHUD dismissWithDelay:0.1];

       [[self allSessionTask] removeObject:task];

       NSDictionary *response = (NSDictionary *)responseObject;

       NSInteger code = ((NSNumber *)response[@"code"]).integerValue;
       if (code == 203) {
         [Dialog toast:@"登录成功" delay:2];
       }else if(code == 101) {
         
       }else {
         [Dialog toast:(NSString *)responseObject[@"message"] delay:2];
       }

       if (code == 201) {
         [[UserManager sharedUserManager] logout:^(BOOL success, NSString *des) {
         }];
       }

       success ? success(responseObject) : nil;
       
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       
       NSLog(@"error ： %@",error);
       
       [[self allSessionTask] removeObject:task];
       
       failure ? failure(error) : nil;
    }];

    // 添加最新的sessionTask到数组
    sessionTask ? [[self allSessionTask] addObject:sessionTask] : nil ;

    return sessionTask;
}


// key=value形式传参数
+ (__kindof NSURLSessionTask *)POSTNoHUDWithBaseUrlByKeyValue:(NSString *)baseUrl
                                          suffixUrl:(NSString *)suffixUrl
                                         parameters:(id)parameter
                                            success:(WOHttpRquestSuccess)success
                                            failure:(WOHttpRequestFailed)failure {
            
           
       // 拼接成完整的url
       baseUrl = [NSString stringWithFormat:@"%@%@",baseUrl,suffixUrl.length == 0 ? @"" : suffixUrl];
       
       // 将参数转换为字典
       NSDictionary *parameters = [parameter mj_keyValues];
       
       NSLog(@"\n parameters ：%@ \n URL: %@",parameters,baseUrl);
    
       /***
        AFHTTPRequestSerializer：第一种是普通的http的编码格式也就是mid=10&method=userInfo&dateInt=20160818，这种格式的。
        AFJSONRequestSerializer：第二种也是json编码格式的，也就是编码成{“mid”:“11”,“method”:“userInfo”,“dateInt”:“20160818”}
        AFPropertyListRequestSerializer：第三种没用过，但是看介绍接编码成pislt格式的参数
        */
       _sessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
       [_sessionManager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

       NSMutableDictionary *heards = [NSMutableDictionary dictionary];
       NSString *token = [[UserManager sharedUserManager] getToken];

       if (token != nil) {
           [heards setObject:[NSString stringWithFormat:@"Bearer %@",token] forKey:@"Authorization"];
       }
       
       NSURLSessionTask *sessionTask = [_sessionManager POST:baseUrl parameters:parameters headers:heards  progress:^(NSProgress * _Nonnull uploadProgress) {
           
       } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    
           [[self allSessionTask] removeObject:task];

           NSDictionary *response = (NSDictionary *)responseObject;

           NSInteger code = ((NSNumber *)response[@"code"]).integerValue;
           if (code == 203) {
             [Dialog toast:@"登录成功" delay:2];
           }else if(code == 101) {
             
           }else {
             [Dialog toast:(NSString *)responseObject[@"message"] delay:2];
           }

           if (code == 201) {
             [[UserManager sharedUserManager] logout:^(BOOL success, NSString *des) {
             }];
           }

           success ? success(responseObject) : nil;
           
       } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
           
           NSLog(@"error ： %@",error);
           
           [[self allSessionTask] removeObject:task];
           
           failure ? failure(error) : nil;
       }];
       
       // 添加最新的sessionTask到数组
       sessionTask ? [[self allSessionTask] addObject:sessionTask] : nil ;
       
       return sessionTask;
}


+ (NSString*)dictionaryToJson:(NSDictionary *)dic {
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

#pragma mark - GET
+ (NSURLSessionTask *)GETWithBaseUrl:(NSString *)baseUrl
                           suffixUrl:(NSString *)suffixUrl
                          parameters:(id)parameter
                             success:(WOHttpRquestSuccess)success
                             failure:(WOHttpRequestFailed)failure {
    
    // 拼接url
    baseUrl = [NSString stringWithFormat:@"%@%@",baseUrl,suffixUrl.length == 0 ? @"" : suffixUrl];
    
    // 检查地址中是否有中文
    baseUrl = [NSURL URLWithString:baseUrl] ? baseUrl : [self strUTF8Encoding:baseUrl];
    
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    [SVProgressHUD show];
    
    // 将参数转换为字典
    NSDictionary *parameters = [parameter mj_keyValues];
    
    NSLog(@"\n parameters ：%@ \n URL: %@",parameters,baseUrl);
    
    NSMutableDictionary *heards = [NSMutableDictionary dictionary];
    NSString *token = [[UserManager sharedUserManager] getToken];

    if (token != nil) {
        [heards setObject:[NSString stringWithFormat:@"Bearer %@",token] forKey:@"Authorization"];
    }
    
    NSURLSessionTask *sessionTask = [_sessionManager GET:baseUrl parameters:parameters headers:heards  progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    
        // 取消指示器
        [SVProgressHUD dismissWithDelay:0.1];
              
        [[self allSessionTask] removeObject:task];
        
        NSDictionary *response = (NSDictionary *)responseObject;

        NSInteger code = ((NSNumber *)response[@"code"]).integerValue;
        if (code == 203) {
            [Dialog toast:@"登录成功" delay:2];
        }else if(code == 101) {
            
        }else {
            [Dialog toast:(NSString *)responseObject[@"message"] delay:2];
        }
        
        if (code == 201) {
            [[UserManager sharedUserManager] logout:^(BOOL success, NSString *des) {}];
        }

        success ? success(responseObject) : nil;
                
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"error ： %@",error);
        
        [[self allSessionTask] removeObject:task];
        
        // 请求失败提示
        [self errorDomainTips:error];
        
        failure ? failure(error) : nil;
    }];
    
    // 添加sessionTask到数组
    sessionTask ? [[self allSessionTask] addObject:sessionTask] : nil ;
    
    return sessionTask;
}

+ (void)permissionToFailure:(id)responData {
    
    if ([responData[@"status"] isKindOfClass:[NSNumber class]]) {
        
        NSInteger status = [responData[@"status"] integerValue];
        switch (status) {
            case 1:
                {
                    NSLog(@"验证失效，请重新登录！");
                    [WOAlert alertShowTitle:@"提示" message:@"验证失效，请重新登录！" cancelButtonTitle:@"取消" otherButtonTitles:@"确定" block:^(NSInteger buttonIndex) {
                        if (buttonIndex == 1) {
//                            [MASUserManageCenter logout];
                        }
                    }];
                }
                break;
                
            default:
                break;
        }
    }
}

// 请求失败提示
+ (void)errorDomainTips:(NSError *)error {
    
    [SVProgressHUD dismiss];
    switch (error.code) {
        case NSURLErrorTimedOut:
            [SVProgressHUD showErrorWithStatus:@"请求超时!"];
            break;
            
        case NSURLErrorNotConnectedToInternet:
            [SVProgressHUD showInfoWithStatus:@"网络已断开,请检查网络!"];
            break;
            
        default:
            [SVProgressHUD showErrorWithStatus:@"请求失败!"];
            break;
    }
    
    // 取消指示器
    [SVProgressHUD dismissWithDelay:1];
}

+ (NSURLSessionTask *)GETNoHUDWithBaseUrl:(NSString *)baseUrl
                           suffixUrl:(NSString *)suffixUrl
                          parameters:(id)parameter
                             success:(WOHttpRquestSuccess)success
                             failure:(WOHttpRequestFailed)failure {
    
    // 拼接url
    baseUrl = [NSString stringWithFormat:@"%@%@",baseUrl,suffixUrl.length == 0 ? @"" : suffixUrl];
    
    // 检查地址中是否有中文
    baseUrl = [NSURL URLWithString:baseUrl] ? baseUrl : [self strUTF8Encoding:baseUrl];
    
    // 将参数转换为字典
    NSDictionary *parameters = [parameter mj_keyValues];
    
    NSLog(@"\n parameters ：%@ \n URL: %@",parameters,baseUrl);
    
    NSMutableDictionary *heards = [NSMutableDictionary dictionary];
    NSString *token = [[UserManager sharedUserManager] getToken];

    if (token != nil) {
        [heards setObject:[NSString stringWithFormat:@"Bearer %@",token] forKey:@"Authorization"];
    }

    NSURLSessionTask *sessionTask = [_sessionManager GET:baseUrl parameters:parameters headers:heards  progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

         [[self allSessionTask] removeObject:task];
         
         NSDictionary *response = (NSDictionary *)responseObject;

         NSInteger code = ((NSNumber *)response[@"code"]).integerValue;
         if (code == 203) {
             [Dialog toast:@"登录成功" delay:2];
         }else if(code == 101) {
             
         }else {
             [Dialog toast:(NSString *)responseObject[@"message"] delay:2];
         }
         
         if (code == 201) {
             [[UserManager sharedUserManager] logout:^(BOOL success, NSString *des) {}];
         }

         success ? success(responseObject) : nil;

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"error ： %@",error);
        
        [[self allSessionTask] removeObject:task];
        
        // 请求失败提示
        [self errorDomainTips:error];
        
        failure ? failure(error) : nil;
    }];
    
    // 添加sessionTask到数组
    sessionTask ? [[self allSessionTask] addObject:sessionTask] : nil ;
    
    return sessionTask;
}

+ (__kindof NSURLSessionTask *)GETWithBaseUrl:(NSString *)baseUrl
                                    suffixUrl:(NSString *)suffixUrl
                                   parameters:(id)parameter
                                responseCache:(WOHttpRequestCache)responseCache
                                      success:(WOHttpRquestSuccessWithCache)success
                                      failure:(WOHttpRequestFailed)failure {
    
    // 拼接url
    baseUrl = [NSString stringWithFormat:@"%@%@",baseUrl,suffixUrl.length == 0 ? @"" : suffixUrl];
    
    // 检查地址中是否有中文
    baseUrl = [NSURL URLWithString:baseUrl] ? baseUrl : [self strUTF8Encoding:baseUrl];
    
    // 将参数转换为字典
    NSDictionary *parameters = [parameter mj_keyValues];
    
    //读取缓存
    responseCache!=nil ? responseCache([WONetworkCache httpCacheForURL:baseUrl parameters:parameters]) : nil;
    
    NSDictionary *heards = NULL;

    NSURLSessionTask *sessionTask = [_sessionManager GET:baseUrl parameters:parameters headers:heards  progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [[self allSessionTask] removeObject:task];
        //对数据进行异步缓存
        responseCache!=nil ? [WONetworkCache setHttpCache:responseObject URL:baseUrl parameters:parameters withBlock:^{
            NSLog(@"++++++  %d",[NSThread isMainThread]);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                success ? success(responseObject, YES) : nil;
            });
        }] : nil;
        
//        [[Dialog Instance] hideHUD];
        
        [self permissionToFailure:responseObject];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error ： %@",error);

        [[self allSessionTask] removeObject:task];
        failure ? failure(error) : nil;
//        [[Dialog Instance] hideHUD];
    }];
    
    // 添加sessionTask到数组
    sessionTask ? [[self allSessionTask] addObject:sessionTask] : nil ;
    return sessionTask;
}

#pragma mark - upload file
+ (__kindof NSURLSessionTask *)uploadFileWithBaselURL:(NSString *)baseUrl
                                              suffixUrl:(nullable NSString *)suffixUrl
                                             parameters:(id)parameters
                                                   name:(NSString *)name
                                               filePath:(NSString *)filePath
                                               progress:(WOHttpProgressBlock)progress
                                                success:(WOHttpRquestSuccess)success
                                                failure:(WOHttpRequestFailed)failure {
    
    // 拼接url
    baseUrl = [NSString stringWithFormat:@"%@%@",baseUrl,suffixUrl.length == 0 ? @"" : suffixUrl];
    
    // 将参数转换为字典
    NSDictionary *parameterDict = [parameters mj_keyValues];
    
    NSDictionary *heards = NULL;

    NSURLSessionTask *sessionTask = [_sessionManager POST:baseUrl parameters:parameterDict headers:heards  constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSError *error = nil;
        [formData appendPartWithFileURL:[NSURL URLWithString:filePath] name:name error:&error];
        (failure && error) ? failure(error) : nil;
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //上传进度
        dispatch_sync(dispatch_get_main_queue(), ^{
            progress ? progress(uploadProgress.completedUnitCount, uploadProgress.totalUnitCount) : nil;
        });
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        success ? success(responseObject) : nil;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failure ? failure(error) : nil;
    }];
    
    return sessionTask;
}

#pragma mark - 上传单/多张图片
+ (__kindof NSURLSessionTask *)uploadImagesWithBaseURL:(NSString *)baseUrl
                                             suffixUrl:(nullable NSString *)suffixUrl
                                            parameters:(id)parameters
                                                  name:(NSString *)name
                                                images:(NSArray<UIImage *> *)images
                                             fileNames:(NSArray<NSString *> *)fileNames
                                            imageScale:(CGFloat)imageScale
                                             imageType:(NSString *)imageType
                                              progress:(WOHttpProgressBlock)progress
                                               success:(WOHttpRquestSuccess)success
                                               failure:(WOHttpRequestFailed)failure {
    
    // 拼接url
    baseUrl = [NSString stringWithFormat:@"%@%@",baseUrl,suffixUrl.length == 0 ? @"" : suffixUrl];
    
    // 将参数转换为字典
    NSDictionary *parameterDict = [parameters mj_keyValues];
    
    // 显示指示器
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    [SVProgressHUD show];
    
    NSDictionary *heards = NULL;

    NSURLSessionTask *sessionTask = [_sessionManager POST:baseUrl parameters:parameterDict headers:heards  constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        for (NSUInteger i = 0; i < images.count; i++) {
           
            // 图片经过等比压缩后得到的二进制文件
            NSData *imageData = UIImageJPEGRepresentation(images[i], imageScale ?: 1.f);
            
            // 默认图片的文件名, 若fileNames为nil就使用
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *imageFileName = NSStringFormat(@"%@%ld.%@",str,i,imageType?:@"jpg");
            
            [formData appendPartWithFileData:imageData
                                        name:imageFileName
                                    fileName:fileNames ? NSStringFormat(@"%@.%@",fileNames[i],imageType?:@"jpg") : imageFileName
                                    mimeType:NSStringFormat(@"image/%@",imageType ?: @"jpg")];
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //上传进度
        dispatch_sync(dispatch_get_main_queue(), ^{
            progress ? progress(uploadProgress.completedUnitCount, uploadProgress.totalUnitCount) : nil;
        });
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // 取消指示器
        [SVProgressHUD dismissWithDelay:0.1];
        [[self allSessionTask] removeObject:task];

        success ? success(responseObject) : nil;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [[self allSessionTask] removeObject:task];

        failure ? failure(error) : nil;
        
        // 请求失败提示
        [self errorDomainTips:error];
    }];
    
    return sessionTask;
}


#pragma mark - 上传单/多视频
+ (__kindof NSURLSessionTask *)uploadVideoWithBaseURL:(NSString *)baseUrl
                                             suffixUrl:(nullable NSString *)suffixUrl
                                            parameters:(id)parameters
                                                  name:(NSString *)name
                                                videoFilePaths:(NSArray <NSURL *> *)videoFilePaths
                                             fileNames:(NSArray<NSString *> *)fileNames
                                             mediaType:(NSString *)mediaType
                                              progress:(WOHttpProgressBlock)progress
                                               success:(WOHttpRquestSuccess)success
                                               failure:(WOHttpRequestFailed)failure {
    
    // 拼接url
    baseUrl = [NSString stringWithFormat:@"%@%@",baseUrl,suffixUrl.length == 0 ? @"" : suffixUrl];
    
    // 将参数转换为字典
    NSDictionary *parameterDict = [parameters mj_keyValues];
    
    // 显示指示器
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    [SVProgressHUD show];
    
    NSDictionary *heards = NULL;

    NSURLSessionTask *sessionTask = [_sessionManager POST:baseUrl parameters:parameterDict headers:heards  constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        for (NSUInteger i = 0; i < videoFilePaths.count; i++) {
           
            // 图片经过等比压缩后得到的二进制文件
            NSURL *fileUrl = videoFilePaths[i];
 
              NSData *videoData = [NSData dataWithContentsOfURL: fileUrl];
//              [formData appendPartWithFileData:videoData name:@"file" fileName:@"video1.mov" mimeType:@"video/quicktime"];
            
            // mov
 
            // 默认图片的文件名, 若fileNames为nil就使用
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = NSStringFormat(@"%@%ld.%@",str,i,mediaType?:@"mp4");
            
            [formData appendPartWithFileData:videoData
                                        name:fileName
                                    fileName:fileNames ? NSStringFormat(@"%@.%@",fileNames[i],mediaType?:@"mp4") : fileName
                                    mimeType:NSStringFormat(@"video/%@",mediaType ?: @"mp4")];
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //上传进度
        dispatch_sync(dispatch_get_main_queue(), ^{
            progress ? progress(uploadProgress.completedUnitCount, uploadProgress.totalUnitCount) : nil;
        });
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // 取消指示器
        [SVProgressHUD dismissWithDelay:0.1];
        [[self allSessionTask] removeObject:task];

        success ? success(responseObject) : nil;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [[self allSessionTask] removeObject:task];

        failure ? failure(error) : nil;
        
        // 请求失败提示
        [self errorDomainTips:error];
    }];
    
    return sessionTask;
}


+ (__kindof NSURLSessionTask *)batchUploadFileWithBaseURL:(NSString *)baseUrl
                                             suffixUrl:(nullable NSString *)suffixUrl
                                            parameters:(id)parameters
                                                  name:(NSString *)name
                                                filePaths:(NSArray <NSURL *> *)filePaths
                                             fileNames:(NSArray<NSString *> *)fileNames
                                             mediaType:(NSString *)mediaType
                                              progress:(WOHttpProgressBlock)progress
                                               success:(WOHttpRquestSuccess)success
                                               failure:(WOHttpRequestFailed)failure {
    
    // 拼接url
    baseUrl = [NSString stringWithFormat:@"%@%@",baseUrl,suffixUrl.length == 0 ? @"" : suffixUrl];
    
    // 将参数转换为字典
    NSDictionary *parameterDict = [parameters mj_keyValues];
    
    // 显示指示器
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    [SVProgressHUD show];
    
    NSDictionary *heards = NULL;

    NSURLSessionTask *sessionTask = [_sessionManager POST:baseUrl parameters:parameterDict headers:heards  constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        for (NSUInteger i = 0; i < filePaths.count; i++) {
           
            // 图片经过等比压缩后得到的二进制文件
            NSURL *fileUrl = filePaths[i];
            
            NSString *fileType = [fileUrl pathExtension]; // 文件类型 如mp4、aac
            NSString *name = NSStringFormat(@"file-%ld", i); // 批量上传的name必须不一样
            NSData *videoData = [NSData dataWithContentsOfURL: fileUrl];
 
            if (videoData == nil) { 
                failure([NSError errorWithDomain:NSURLErrorDomain code:NSUnderlyingErrorKey userInfo:nil]);
                return;
            }
            
            // 默认图片的文件名, 若fileNames为nil就使用
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = NSStringFormat(@"%@%ld.%@",str,i, fileType);
            
            [formData appendPartWithFileData:videoData
                                        name:name
                                    fileName:fileName
                                    mimeType:fileType];
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //上传进度
        dispatch_sync(dispatch_get_main_queue(), ^{
            progress ? progress(uploadProgress.completedUnitCount, uploadProgress.totalUnitCount) : nil;
        });
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // 取消指示器
        [SVProgressHUD dismissWithDelay:0.1];
        [[self allSessionTask] removeObject:task];

        success ? success(responseObject) : nil;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [[self allSessionTask] removeObject:task];

        failure ? failure(error) : nil;
        
        // 请求失败提示
        [self errorDomainTips:error];
    }];
    
    return sessionTask;
}


/*
 @paramdata图片或视频二进制数据
 @paramname 对应服务器的字段名
 @paramfileName 文件名，后缀要跟文件类型一致，不能为空
 @parammimeType 文件类型 举例image/pngvideo/quicktime
 */
+ (__kindof NSURLSessionTask *)uploadFileWithMediaDataWithBaseURL:(NSString *)baseUrl
                                             suffixUrl:(nullable NSString *)suffixUrl
                                            parameters:(id)parameters
                                                  name:(NSString *)name
                                                images:(NSMutableArray *)mediaDatas
                                             fileNames:(NSArray<NSString *> *)fileNames
                                            imageScale:(CGFloat)imageScale
                                             imageType:(NSString *)imageType
                                              progress:(WOHttpProgressBlock)progress
                                               success:(WOHttpRquestSuccess)success
                                               failure:(WOHttpRequestFailed)failure {
    
    // 拼接url
    baseUrl = [NSString stringWithFormat:@"%@%@",baseUrl,suffixUrl.length == 0 ? @"" : suffixUrl];
    
    // 将参数转换为字典
    NSDictionary *parameterDict = [parameters mj_keyValues];
    
    // 显示指示器
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    [SVProgressHUD show];
    
    NSDictionary *heards = NULL;

    NSURLSessionTask *sessionTask = [_sessionManager POST:baseUrl parameters:parameterDict headers:heards  constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//        
//        for (NSUInteger i = 0; i < mediaDatas.count; i++) {
//            NSObject *firstObj = mediaDatas[i];
//            if ([firstObj isKindOfClass:[UIImage class]]) {
//                // 图片
//                for(NSInteger i=0; i<mediaDatas.count;i++){
//                    UIImage *eachImg = (UIImage *)firstObj;
//                    //NSData *eachImgData = UIImagePNGRepresentation(eachImg);
//                    NSData *eachImgData = UIImageJPEGRepresentation(eachImg, 0.5);
//                    [formData appendPartWithFileData:eachImgData name:@"file" fileName:[NSString stringWithFormat:@"img%ld.png", i+1] mimeType:@"image/png"];
//                }
//            }else if([firstObj isKindOfClass:[ALAsset class]]){
//                // 视频
//                ALAsset *asset = (ALAsset *)firstObj;
//                NSLog(@"asset=%@, representation=%@, url=%@", asset, [asset defaultRepresentation], [asset defaultRepresentation].url);
//                if (asset != nil) {
//                    NSArray *documentPaths= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//                    NSString *docuPath = [documentPaths objectAtIndex:0];
//                    NSString *videoPath= [docuPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.mov", 0]];    // 这里直接强制写一个即可，之前计划是用i++来区分不明视频
//                    NSURL *url = [NSURL fileURLWithPath:videoPath];
//                    NSError *theErro = nil;
//                    BOOL exportResult = [asset exportDataToURL:url error:&theErro];
//                    NSLog(@"exportResult=%@", exportResult?@"YES":@"NO");
//                    NSData *videoData = [NSData dataWithContentsOfURL:url];
//                    [formData appendPartWithFileData:videoData name:@"file" fileName:@"video1.mov" mimeType:@"video/quicktime"];
//                }
//            }
//        }
//        
//        
//        
//        for (NSUInteger i = 0; i < images.count; i++) {
//           
//            // 图片经过等比压缩后得到的二进制文件
//            NSData *imageData = UIImageJPEGRepresentation(images[i], imageScale ?: 1.f);
//            
//            // 默认图片的文件名, 若fileNames为nil就使用
//            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//            formatter.dateFormat = @"yyyyMMddHHmmss";
//            NSString *str = [formatter stringFromDate:[NSDate date]];
//            NSString *imageFileName = NSStringFormat(@"%@%ld.%@",str,i,imageType?:@"jpg");
//            
//            [formData appendPartWithFileData:imageData
//                                        name:imageFileName
//                                    fileName:fileNames ? NSStringFormat(@"%@.%@",fileNames[i],imageType?:@"jpg") : imageFileName
//                                    mimeType:NSStringFormat(@"image/%@",imageType ?: @"jpg")];
//        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //上传进度
        dispatch_sync(dispatch_get_main_queue(), ^{
            progress ? progress(uploadProgress.completedUnitCount, uploadProgress.totalUnitCount) : nil;
        });
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // 取消指示器
        [SVProgressHUD dismissWithDelay:0.1];
        [[self allSessionTask] removeObject:task];

        success ? success(responseObject) : nil;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [[self allSessionTask] removeObject:task];

        failure ? failure(error) : nil;
        
        // 请求失败提示
        [self errorDomainTips:error];
    }];
    
    return sessionTask;
}



#pragma mark - 上传单张图片
+ (__kindof NSURLSessionTask *)uploadImagesWithBaseURL:(NSString *)baseUrl
                                             suffixUrl:(nullable NSString *)suffixUrl
                                            parameters:(id)parameters
                                                  name:(NSString *)name
                                                 image:(UIImage *)image
                                              fileName:(NSString *)fileName
                                            imageScale:(CGFloat)imageScale
                                             imageType:(NSString *)imageType
                                              progress:(WOHttpProgressBlock)progress
                                               success:(WOHttpRquestSuccess)success
                                               failure:(WOHttpRequestFailed)failure {
    
    // 拼接url
    baseUrl = [NSString stringWithFormat:@"%@%@",baseUrl,suffixUrl.length == 0 ? @"" : suffixUrl];
    
    // 将参数转换为字典
    NSDictionary *parameterDict = [parameters mj_keyValues];
    
    // 显示指示器
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    [SVProgressHUD show];
    
    NSDictionary *heards = NULL;

    NSURLSessionTask *sessionTask = [_sessionManager POST:baseUrl parameters:parameterDict headers:heards  constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        // 图片经过等比压缩后得到的二进制文件
        NSData *imageData = UIImageJPEGRepresentation(image, imageScale ?: 1.f);
        
        // 默认图片的文件名, 若fileNames为nil就使用
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *imageFileName = NSStringFormat(@"%@%ld.%@",str,0,imageType?:@"jpg");
        
        [formData appendPartWithFileData:imageData
                                    name:name
                                fileName:fileName ? NSStringFormat(@"%@.%@",fileName,imageType?:@"jpg") : imageFileName
                                mimeType:NSStringFormat(@"image/%@",imageType ?: @"jpg")];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //上传进度
        dispatch_sync(dispatch_get_main_queue(), ^{
            progress ? progress(uploadProgress.completedUnitCount, uploadProgress.totalUnitCount) : nil;
        });
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
//        // 取消指示器
//        [SVProgressHUD dismiss];
        
        success ? success(responseObject) : nil;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failure ? failure(error) : nil;
        
        // 请求失败提示
        [self errorDomainTips:error];
    }];
    
    return sessionTask;
}

#pragma mark - 下载文件
+ (__kindof NSURLSessionTask *)downloadWithBaseUrlURL:(NSString *)baseUrl
                                            suffixUrl:(nullable NSString *)suffixUrl
                                           saveToPath:(NSString *)saveToPath
                                             progress:(WOHttpProgressBlock)progress
                                              success:(WOHttpRquestSuccess)success
                                              failure:(WOHttpRequestFailed)failure {
    
    // 拼接url
    baseUrl = [NSString stringWithFormat:@"%@%@",baseUrl,suffixUrl.length == 0 ? @"" : suffixUrl];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:baseUrl]];
    
    __block NSURLSessionDownloadTask *downloadTask = [_sessionManager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        
        //下载进度
        dispatch_sync(dispatch_get_main_queue(), ^{
            progress ? progress(downloadProgress.completedUnitCount, downloadProgress.totalUnitCount) : nil;
        });
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
//        NSString *fileName;
//        //拼接缓存目录
//        NSString *downloadDir = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:fileName ? fileName : @"Download"];
//        //打开文件管理器
//        NSFileManager *fileManager = [NSFileManager defaultManager];
//        //创建Download目录
//        [fileManager createDirectoryAtPath:downloadDir withIntermediateDirectories:YES attributes:nil error:nil];
//        //拼接文件路径
//        NSString *filePath = [downloadDir stringByAppendingPathComponent:response.suggestedFilename];
        
        //返回文件位置的URL路径
        return [NSURL fileURLWithPath:saveToPath];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
        if(failure && error) {failure(error) ; return ;};
        success ? success(filePath.absoluteString /** NSURL->NSString*/) : nil;
        
    }];
    
    // 开始下载
    [downloadTask resume];
    return downloadTask;
}

#pragma mark - 监控当前网络变化
+ (void)checkNetworkStatus
{
    NSURL *url=[NSURL URLWithString:@"www.baidu.com"];
    AFHTTPSessionManager *operationManager=[[AFHTTPSessionManager alloc]initWithBaseURL:url];
    /*
     AFNetworkReachabilityStatusUnknown          = -1,
     AFNetworkReachabilityStatusNotReachable     = 0,
     AFNetworkReachabilityStatusReachableViaWWAN = 1,
     AFNetworkReachabilityStatusReachableViaWiFi = 2,
     
     [operationManager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
     switch (status) {
     case AFNetworkReachabilityStatusReachableViaWiFi:
     NSLog(@"WIFI Connection");
     break;
     case AFNetworkReachabilityStatusReachableViaWWAN:
     NSLog(@"2G/3G/4G Connection");
     break;
     case AFNetworkReachabilityStatusNotReachable:
     NSLog(@"Network not found");
     break;
     default:
     NSLog(@"Unknown");
     break;
     }
     }];*/
    //开始监控
    [operationManager.reachabilityManager startMonitoring];
}

#pragma mark - 开始监听网络
+ (void)networkStatusWithBlock:(WONetworkStatusBlock)networkStatus {

    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                networkStatus ? networkStatus(WONetworkStatusUnknown) : nil;
                NSLog(@"未知网络");
                break;
            case AFNetworkReachabilityStatusNotReachable:
                networkStatus ? networkStatus(WONetworkStatusNotReachable) : nil;
                 NSLog(@"无网络");
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                networkStatus ? networkStatus(WONetworkStatusReachableViaWWAN) : nil;
                NSLog(@"手机自带网络");
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                networkStatus ? networkStatus(WONetworkStatusReachableViaWiFi) : nil;
                NSLog(@"WIFI");
                break;
        }
    }];
    
}

/**
 存储着所有的请求task数组
 */
+ (NSMutableArray *)allSessionTask {
    if (!_allSessionTask) {
        _allSessionTask = [[NSMutableArray alloc] init];
    }
    return _allSessionTask;
}

#pragma mark - 取消指定URL的HTTP请求

+ (void)cancelAllRequest {
    // 锁操作
    @synchronized(self) {
        [[self allSessionTask] enumerateObjectsUsingBlock:^(NSURLSessionTask  *_Nonnull task, NSUInteger idx, BOOL * _Nonnull stop) {
            [task cancel];
        }];
        [[self allSessionTask] removeAllObjects];
    }
}

+ (void)cancelRequestWithURL:(NSString *)URL {
    if (!URL) { return; }
    @synchronized (self) {
        [[self allSessionTask] enumerateObjectsUsingBlock:^(NSURLSessionTask  *_Nonnull task, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([task.currentRequest.URL.absoluteString hasPrefix:URL]) {
                [task cancel];
                [[self allSessionTask] removeObject:task];
                *stop = YES;
            }
        }];
    }
}

#pragma mark - 网络状态
+ (BOOL)isNetwork {
    return [AFNetworkReachabilityManager sharedManager].reachable;
}

+ (BOOL)isWWANNetwork {
    return [AFNetworkReachabilityManager sharedManager].reachableViaWWAN;
}

+ (BOOL)isWiFiNetwork {
    return [AFNetworkReachabilityManager sharedManager].reachableViaWiFi;
}

#pragma mark - 把url中的中文转为utf-8编码
+ (NSString *)strUTF8Encoding:(NSString *)str{
    
    if (IOS_VERSION >= 9.0) {
      return [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    }else
        return [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

@end
